package org.webdb.jdbc;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.webdb.core.DocumentRecord;

public class JDBCDocumentRecord implements DocumentRecord {

    protected Map<String, Object> map = new HashMap<String, Object>();
    private ResultSet resultSet;

    public JDBCDocumentRecord(JDBCTable table, ResultSet rs)
            throws SQLException {
        for (JDBCColumn column : table.getColumns()) {
            map.put(column.getName(), rs.getObject(column.getName()));
        }
        this.resultSet = rs;
    }

    public Set<Entry<String, Object>> fieldEntrySet() {
        return map.entrySet();
    }

    public void close() throws IOException {
        JDBCUtils.close(resultSet);
    }

    public Object getField(String columnName) {
        return searchColumn(columnName);
    }

    private Object searchColumn(String columnName) {
        for (Entry<String, Object> entry : map.entrySet()) {
            if (columnName.equalsIgnoreCase(entry.getKey()))
                return entry.getValue();
        }
        return null;
    }

    public boolean isEmpty() {
        return map.isEmpty();
    }

}
